package com.springcloud.gateway.dynamic;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/10/31 11:32
 * @description
 * @Modify By：
 * @ModifyTime： 2019/10/31
 * @Modify marker：
 **/
@Slf4j
@Component
public class DynamicRouteServiceListenner {
    private final DynamicRouteService dynamicRouteService;
    public DynamicRouteServiceListenner(DynamicRouteService dynamicRouteService){
        this.dynamicRouteService=dynamicRouteService;
        dynamicRouteServiceListener();
    }
    private void  dynamicRouteServiceListener(){
        try {
            String dataId="gatewayroute";
            String group="DEFAULT_GROUP";
            String serverAddr="127.0.0.1:8848";


            //连接nacos  实例
            ConfigService configService= NacosFactory.createConfigService(serverAddr);
            log.info("aaaa:{}",configService.getServerStatus());

            //添加监听事件
            configService.addListener(dataId, group, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    List<RouteDefinition> routeDefinitionList = JSON.parseArray(configInfo,RouteDefinition.class);
                    dynamicRouteService.updateList(routeDefinitionList);

                }
            });

            String configInfo=configService.getConfig(dataId,group,5000);

            log.info("sssss:{}",configInfo);
            if(configInfo!=null){
                List<RouteDefinition> routeDefinitions=JSON.parseArray(configInfo,RouteDefinition.class);
                dynamicRouteService.updateList(routeDefinitions);
            }
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}
